<template>
  <View class="container">
    <login v-if="!isLogined && isShow" v-on:x="noLogin" v-on:plogin="toLogin" sourcePage="newPeopleTask" :source="source"
      :invitorCode="invitorCode"></login>
    <template v-if="taskStatus">
      <navigation-bar @onBack="onBack()"
        :navigationStyle="{ background: taskStatus === 'Expired' && !isPending ? 'transparent' : '#FD3236', position: taskStatus === 'Expired' && !isPending ? 'fixed' : 'relative' }"
        title="新人任务" />
      <template v-if="taskStatus === 'Expired' && !isPending">
        <View class="expire-page">
          <image mode="aspectFill" :src="`${imgBasePath}newtask/expire-bg.png`" class="expire-bg"></image>
          <taskCard :activityDetail="activityDetail" :motivations="motivations" @onReceiveReward="onReceiveReward" />
        </View>
      </template>
      <template v-else>
        <scroll-view :scroll-y="true" :scroll-into-view="scrollIntoView" class="not-expire-page" :style="{height: `calc(100% - ${contentTop})`}" @scroll="scroll()">
          <image mode="aspectFill" :src="`${imgBasePath}newtask/header-bg.png`" class="header-bg"></image>
          <taskCard :activityDetail="activityDetail" :motivations="motivations" @onReceiveReward="onReceiveReward" />
          <image v-if="taskStatus === 'OnGoing'" mode="widthFix" :src="`${imgBasePath}newtask/cash-tip.png`"
            class="cash-tip"></image>
          <View class="count-down" v-if="taskStatus === 'OnGoing'">
            距离任务结束仅剩<Text class="number">{{ countDown.days }}</Text>天<Text class="number">{{ countDown.hours
            }}</Text>时<Text class="number">{{ countDown.minutes }}</Text>分<Text class="number">{{ countDown.seconds
}}</Text>秒
          </View>
          <View class="task-list">
            <View class="item" v-for="(item, index) in tasks" :key="index" :id="'task_' + index">
              <View class="item-left">
                <Text class="task-name">{{ item.taskTitle }}</Text>
                <View class="reward">
                  <image :src="`${imgBasePath}newtask/reward-icon.png`" class="reward-icon"></image>
                  <Text class="amount">{{ item.reward }}元</Text>
                </View>
              </View>
              <View class="completed-button" v-if="activityDetail.userActivityStatus == 'Expired' && item.userTaskStatus != 'Done'">
                <Text class="completed-text">未完成</Text>
              </View>
              <View class="not-completed-button" v-else-if="item.progress == 0 && item.userTaskStatus == 'OnGoing'" @click="goDoTask(item)">
                <Text>去完成</Text>
                <image v-if="scrollInfoIndex === index" :src="`${imgBasePath}newtask/gesture.png`"
                  class="gesture"></image>
              </View>
              <View class="not-completed-button" v-else-if="item.progress > 0 && item.userTaskStatus == 'OnGoing'" @click="goDoTask(item)">
                <Text>差{{ item.contentNum - item.progress }}个</Text>
                <image :src="`${imgBasePath}newtask/gesture.png`" class="gesture"></image>
              </View>
              <View class="completed-button" v-else-if="item.userTaskStatus == 'Done'">
                <image :src="`${imgBasePath}newtask/tick.png`"></image>
                <Text class="completed-text">已完成</Text>
              </View>
            </View>
          </View>
          <View class="danger-tip">
            活动奖励以实际发放为准。本公司对活动拥有最终解释权，如有疑问可联系您的店长。</View>
        </scroll-view>
      </template>
    </template>
    <View class="mask" v-if="source === -1">
      <View class="share-wrap">
        <image class="share-button-bg" mode="widthFix" :src="`${imgBasePath}newtask/share-button-bg.png`" />
        <button class="button" open-type="share">点击分享到微信群或微信用户</button>
      </View>
      <image class="share-arrow" mode="widthFix" :src="`${imgBasePath}newtask/share-arrow.png`" />
    </View>
  </View>
</template>
<script>
import taskCard from "./components/task-card.vue";
import navigationBar from "./components/navigation-bar.vue";
import { imgBasePath, trackingHost, stateHost } from "@/common/config";

export default {
  components: {
    taskCard,
    navigationBar,
  },
  data() {
    return {
      activityDetail: {}, 
      remainingTime: 0,
      scrollIntoView: "",
      scrollInfoIndex: null,
      motivations: [],
      menuHeight: uni.getStorageSync('menuInfo').menuHeight,
      imgBasePath,
      startTime: Date.parse(new Date()),
      contentTop: uni.getStorageSync('menuInfo').contentTop,
      isLogined: uni.getStorageSync("token"),
      isShow: true,
      invitorCode: '',
	  source:""
    }
  },
  computed: {
    taskStatus: function () {
      return this.activityDetail.userActivityStatus;
    },
    tasks: function () {
      return this.activityDetail.tasks || [];
    },
    // 活动是否在进行中
    isPending: function () {
      return !!(this.activityDetail.tasks || []).find(item => item.progress > 0);
    },
    countDown: function () {
      const seconds = Math.floor((this.remainingTime / 1000) % 60);
      const minutes = Math.floor((this.remainingTime / 1000 / 60) % 60);
      const hours = Math.floor((this.remainingTime / (1000 * 60 * 60)) % 24);
      const days = Math.floor(this.remainingTime / (1000 * 60 * 60 * 24));
      return {
        days,
        hours: hours > 9 ? hours : `0${hours}`,
        minutes: minutes > 9 ? minutes : `0${minutes}`,
        seconds: seconds > 9 ? seconds : `0${seconds}`,
      }
    }
  },
  onLoad(req) {
    // -1 店长端
    // 1 我的主⻚-新⼈任务
    // 2 新⼈任务分享链接
    // 3 店长分享
    // 4 ⾸⻚悬浮标志
    const { source, invitorCode } = req;
    this.source = +source;
    // 分享带过来的invitorCode
    this.invitorCode = invitorCode;
  },
  onUnload() {
    this.timer && clearInterval(this.timer);
    const endTime = Date.parse(new Date());
    const st = (endTime - this.startTime) / 1000;
    this.activityMain({event: "sessionTime", st});
  },
  onShow() {
    this.timer && clearInterval(this.timer);
    this.isShow = true;
    this.isLogined = uni.getStorageSync("token");
    this.login();
  },
  onShareAppMessage(res) {
    return {
      title: "终于等到你，点击查收新人专属现金红包！",
      imageUrl: `${imgBasePath}newtask/new-task-share.png`,
      path: `/pages/newPeopleTask/index?source=2&invitorCode=${this.invitorCode}`,
    }
  },
  methods: {
    async login() {
      try {
        uni.showLoading({
          title: '加载中'
        });
        const code = await this.wxLogin();
        const checkLoginRes = await this.$NoteApi.doRequest("get", "login", { code, requestCode: '' });
        const { code: checkLoginCode, data, message } = checkLoginRes.data;
        if (checkLoginCode == 0) {
          uni.setStorageSync("userInfo", data);
          uni.setStorageSync("token", data.token);
          await this.activityMain({ event: "impression" });
          if (data.isNew == 1) {
            uni.hideLoading();
            this.isLogined = false;
          } else {
            this.getActivityDetail();
            this.getMotivations();
          }
        } else {
          uni.hideLoading();
          uni.showToast({
            title: message,
            icon: 'none'
          })
        }
      } catch (error) {
        uni.hideLoading();
        uni.showToast({
            title: error,
            icon: 'none'
          })
      }
    },
    wxLogin() {
      return new Promise((resolve, reject) => {
        uni.login({
          provider: 'weixin',
          success: (loginRes) => {
            resolve(loginRes.code)
          },
          fail: (error) => {
            reject(error)
          }
        })
      })
    },
    noLogin() {
      this.isShow = false;
    },
    toLogin() { },
    findCus() {
      return this.$request("api/red/yzkj/findCus", { method: "GET", host: stateHost })
        .then(res => {
          const { storeId, inviteCode: invitorCode } = res;
          this.storeId = storeId;
          this.invitorCode = invitorCode;
          uni.setStorageSync("storeId", storeId);
          return res;
        }).catch(() => null);
    },
    async activityMain({ event, st, element }) {
      // 页面中如果已经有storeId，则不再请求findCus
      if (!this.storeId) {
        await this.findCus();
      }
      const { unionid, openid } = uni.getStorageSync("userInfo");
      const { source, activityDetail } = this;
      const params = {
        oid: openid,
        uid: unionid,
        sid: this.storeId,
        ts: Date.parse(new Date()) / 1000,
        event,
        page: "activityMain",
        source,
        st,
        element,
        status: activityDetail.userActivityStatus
      }
      this.$request("event-tracking/user", { host: trackingHost, params })
        .catch(() => { })
    },
    onBack() {
      if (this.source == 2) {
        uni.switchTab({
          url: '/pages/sindex/index'
        });
      } else {
        uni.navigateBack();
      }
    },
    // 获取任务入口权限
    // getTaskEnterLimits() {
    //   this.$request("marketing/user/activity/available", { params: { source: "MyTaskPage", activityType: "New_People_Task" }, showToast: true })
    //     .then(data => {
    //       if (data.result) {
    //         this.getActivityDetail();
    //         this.getMotivations();
    //       }
    //     }).catch(error => { })
    // },

    // 获取激励人列表
    getMotivations() {
      this.$request("marketing/motivations", { method: "GET", params: {num: 10} })
        .then(data => {
          this.motivations = data;
        })
        .catch(() => { })
    },
    // 获取活动详情
    getActivityDetail() {
      this.$request("marketing/user/activity", { method: "GET", params: { activityType: "New_People_Task" } })
        .then(data => {
          data.reward = data.reward / 100;
          data.tasks.map(item => {
            item.reward = item.reward / 100;
          });

          this.activityDetail = data;
          this.getTemainingTime(data.activityWindEnd);
          uni.hideLoading();
        })
        .catch((error) => {
          uni.hideLoading();
          uni.showModal({
            title: "提示",
            content: error,
            showCancel: false,
            confirmText: "关闭",
            complete: () => {
              uni.switchTab({
                url: '/pages/sindex/index',
              })
            }
          })
        })
    },
    // 计算活动剩余时间
    getTemainingTime(activityWindEnd = 0) {
      const currentTime = new Date().getTime();
      let remainingTime = activityWindEnd - currentTime;
      if (remainingTime < 0) {
        remainingTime = 0;
      }

      this.timer = setInterval(() => {
        remainingTime = remainingTime - 1000;
        if (remainingTime <= 0) {
          return clearInterval(this.timer);
        }
        this.remainingTime = remainingTime;

      }, 1000);
    },
    // 领奖品
    onReceiveReward() {
      const onGoingTaskIndex = this.tasks.findIndex(item => item.userTaskStatus === "OnGoing");
      this.scrollInfoIndex = onGoingTaskIndex;
      this.scrollIntoView = `task_${onGoingTaskIndex}`
    },
    scroll() {
      if (this.scrollIntoView != '') {
        this.scrollIntoView = "";
      }
    },
    // 去做任务
    goDoTask(item) {
      const { taskId, taskType, reward } = item;
      const { activityId } = this.activityDetail;
      this.activityMain({ event: "click", element: taskType })
      if (taskType == "Video") {
        uni.navigateTo({
          url: `/pages/newPeopleTask/taskVideo?taskId=${taskId}&activityId=${activityId}&taskType=${taskType}&reward=${reward}`
        });
      }
      if (taskType == "Store") {
         uni.navigateTo({
          url: `/pages/newPeopleTask/toStore`
        });
      }
      if (taskType == "Video_QA") {
        uni.navigateTo({
          url: `/pages/videoAnswer/index?activityId=${activityId}&taskId=${taskId}&taskType=${taskType}`
        });
      }
    }
  },
}
</script>

<style lang="scss" scoped>
.container {
  height: 100vh;
  background: #FD3236;
  .not-expire-page {
    position: relative;
    background-color: #FD3236;
  }

  .expire-page {
    height: 100vh;
  }

  .expire-bg {
    position: absolute;
    left: 0;
    top: 0;
    width: 100%;
    height: 100%;
  }

  .header-bg {
    position: absolute;
    left: 0;
    top: 0;
    height: 790rpx;
  }

  .cash-tip {
    width: calc(100% - 80rpx);
    margin: 40rpx 0 40rpx 40rpx;
  }

  .count-down {
    display: flex;
    font-family: "PingFangSC-Regular";
    font-size: 29rpx;
    color: #FDE1B4;
    justify-content: center;
    align-items: center;
    margin-bottom: 48rpx;

    .number {
      color: #6F553F;
      margin: 0 14.5rpx;
      font-size: 26rpx;
      width: 36rpx;
      height: 36rpx;
      font-weight: 600;
      text-align: center;
      border-radius: 3.6rpx;
      font-family: PingFangSC-Semibold;
      background-image: linear-gradient(156deg, #FEF2DA 0%, #EBBB8B 100%);
    }
  }

  .task-list {
    padding: 0 33rpx;
    background-color: #FFF7EA;
    margin: 0 27rpx;
    border-radius: 6px;
    position: relative;
    ;
    z-index: 1;

    .item {
      height: 174rpx;
      display: flex;
      align-items: center;
      justify-content: space-between;
      border-bottom: 1rpx solid #F6E4DD;

      .item-left {
        display: flex;
        align-items: center;

        .task-name {
          font-size: 43rpx;
          color: #282828;
          font-weight: 600;
          margin-right: 20rpx;
          font-family: "PingFangSC-Semibold";
        }

        .reward {
          display: flex;
          align-items: center;

          .reward-icon {
            width: 60rpx;
            height: 60rpx;
            margin-right: 5rpx;
          }

          .amount {
            color: #6F553F;
            font-size: 36rpx;
            font-weight: 600;
            font-family: PingFangSC-Semibold;
          }
        }

      }

      .not-completed-button {
        position: relative;
        height: 65rpx;
        min-width: 166rpx;
        line-height: 65rpx;
        font-size: 36rpx;
        color: #fff;
        font-family: PingFangSC-Semibold;
        font-weight: 600;
        text-align: center;
        border-radius: 65rpx;
        background-image: linear-gradient(180deg, #FF7765 0%, #FD3236 100%);

        .gesture {
          position: absolute;
          bottom: -105rpx;
          right: -25rpx;
          width: 100rpx;
          height: 124rpx;
        }
      }

      .completed-button {
        display: flex;
        align-items: center;

        image {
          width: 47rpx;
          height: 47rpx;
          margin-right: 14.5rpx;
        }

        .completed-text {
          font-family: PingFangSC-Semibold;
          font-size: 36.23rpx;
          color: #A5988A;
          font-weight: 600;
        }
      }
    }
  }

  .danger-tip {
    padding: 0 27rpx;
    margin-top: 29rpx;
    color: #FDE1B4;
    font-size: 23.5rpx;
    line-height: 35rpx;
    font-family: "PingFangSC-Regular";
  }

  .mask {
    position: fixed;
    width: 100%;
    height: 100%;
    top: 0;
    left: 0;
    z-index: 10;
    background: rgba(0, 0, 0, 0.50);

    .share-wrap {
      top: 200rpx;
      left: 75rpx;
      position: absolute;
      display: flex;
      align-items: center;
      justify-content: center;
      .share-button-bg {
        width: 430rpx;
      }
      .button {
        padding: 0;
        font-size: 30rpx;
        position: absolute;
        background: none;
        color: #FFFFFF;
        width: 100%;
        &::after {
          border: none;
        }
      }
    }
    .share-arrow {
      position: absolute;
      top: 168rpx;
      right: 145rpx;
      width: 105rpx;
    }
  }

}
</style>
